#pragma once
#include <iostream>
#include <cstring>
#include <cassert>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <functional>
#include <cstdio>
#define NUM 128
using namespace std;
//上下文
class Thread;
class Context
{
public:
    void* _args;
    Thread* _this;
public:
    Context():_args(nullptr),_this(nullptr)
    {}
    ~Context()
    {}
    
};
class Thread
{
    typedef function<void *(void *)> func_t;
    //using func_t = function<void*(void*)>;
public:
    static void* routine(void*args)
    {
        Context* ctx = static_cast<Context*>(args);
        void* ret = ctx->_this->Run(ctx->_args);
        delete ctx;
        return ret;
        
    }
    Thread(func_t func, void *args, int number) : _func(func), _args(args)
    {
        // 吧名字创建出来
        char buffer[NUM];
        snprintf(buffer, sizeof(buffer), "thread-%d", number);
        _name = buffer;
        // 创建线程
        Context* ctx  = new Context();
        ctx->_args = _args;
        ctx->_this = this;
        int n = pthread_create(&_tid,nullptr, routine,ctx);
        assert(n==0);
        (void)n;
    }
    ~Thread()
    {
    }
    void join()
    {
        int n = pthread_join(_tid,nullptr);
        assert(n==0);
        (void)n;
    }
    void* Run(void* args)
    {
        return _func(args);
    }

private:
    string _name;
    void *_args;
    func_t _func;
    pthread_t _tid;
};
